<!-- 单独的户室号匹配 -->
<template>
  <div v-loading="isMatchingBuild" >
    <div class="d-flex ai-center">
      <div class="cell" style="padding: 0 10px">{{ portVO.portType | getPortTypeName }}</div>

      <!-- 匹配 户室号 -->
      <div class="flex-3 cell" v-loading="portVO.hallRoomLoading">
        <div
          v-show="!portVO.hallRoomLoading && portVO.hallRoomNumber.length == 0 && portVO.portResblockName"
          style="margin: auto"
          class="fs-sm text-center"
        >
          加载失败,
          <el-button type="text" @click="handleRetryColumn">点击重试</el-button>
        </div>
        <div class="d-flex">
          <template v-for="item in portVO.hallRoomNumber">
            <!-- 分两种情况 一种是自定义输入 另一种只能点选 -->
            <el-input
              v-if="portVO.huShiHao"
              v-model="portVO[item.key]"
              :key="item.key"
              style="margin: 0 5px; width: 178px;"
              size="mini"
              :class="{ 'reject-input': !portVO[item.key] }"
              :placeholder="item.title"
            ></el-input>
            <el-select
              v-else
              v-model="portVO[item.key]"
              filterable
              remote
              :allow-create="portVO.huShiHao"
              :placeholder="item.title"
              :key="item.key"
              :loading="portVO.singleLoading"
              :disabled="selectDisabled(item.key)"
              :remote-method="remoteMethod(item.key)"
              size="mini"
              @focus="handleFocusHsh('portVO', item.key)"
              @change="handleChangeHsh('portVO', $event)"
              style="margin: 0 5px"
              :class="{ 'reject-input': !portVO[item.key] }"
            >
              <el-option
                v-for="item in portVO.buildUnitDoorOptions"
                :label="item.portBuild || item.portUnit || item.portDoorNum"
                :value="item.platformBuildId || item.platformUnitId || item.platformDoorNumId"
                :key="item.platformBuildId || item.platformUnitId || item.platformDoorNumId"
              ></el-option>
            </el-select>
          </template>
        </div>
      </div>
      <!-- <div :class="['tips1', hushihaoFilledPrue ? 'text-green' : 'text-red', 'text-center']">
        {{hshTips}}
      </div> -->
    </div>
    <div class="tips2">注意：如果下拉框没有对应选项，请输入具体数字进行搜索</div>
  </div>
</template>

<script>
import { hallRoomNumber } from '@/config/house/houseDetailConfig';
import { matchingBuild, matchingUnit, matchinDoorNum, saveHouPortInfo } from '@/api/user';
import { mapState } from 'vuex';
import { EVENT_PLATFORM_RESBLOCKID } from './config';
import { PORT_CODE_AJK } from '@/config/house/platform';

export default {
  name: 'ComHshMatch',
  shulan: true,
  components: {},
  props: {},
  data() {
    return {
      noPortAccount: 1, //默认有账号
      isMatchingBuild: false, // 面积匹配中
      handleTimer: null,
      intervalTime: 2000,
      totalTimes: 0,
      tryTimes: 0,
      popVisible: false,

      modifiedCount: 2, //数据改动的次数（多一次用作初始化时的修改），变为0则表示数据被修改了

      // 端口信息
      portVO: {
        platformResblockId: '', //平台小区id   (platform 代表安居客等平台)
        portResblockName: '', //端口小区名称
        portBuild: '', //栋/幢
        portUnit: '', //单元/号
        portDoorNum: '', //门牌

        platformBuildId: '', //平台楼栋id
        platformUnitId: '', //平台单元ID
        platformDoorNumId: '', //平台门牌号ID

        portType: '', // 平台类型
        hallRoomLoading: false, //户室号加载。。。
        singleLoading: false, //单个户室号加载。。。
        searchKey: '', //搜索关键词
        hallRoomNumber, // 户室号展示 （有几）

        housingEstateOptions: [], //匹配小区选项
        buildUnitDoorOptions: [], //户室号的选项
        huShiHao: false, //是否支持手动输入
        buildSizeLocked: false, //是否建筑面积锁定

        totalPrice: '',
        buildingSize: '',
      },
    };
  },

  created() {
    this.$bus.$on(EVENT_PLATFORM_RESBLOCKID, (id, name) => {
      this.portVO.platformResblockId = id;
      this.portVO.portResblockName = name;
      this.getHshColumn('portVO', this.portVO);
    });
    this.$once('hook:beforeDestroy', () => {
      this.$bus.$off(EVENT_PLATFORM_RESBLOCKID);
    });
  },

  mounted() {
    this.myTotalPrices = this.model.totalPrice;

    this.renderPort(this.model);
  },

  watch: {
    portVO: {
      deep: true,
      handler() {
        this.modifiedCount--;
      },
    },
  },

  computed: {
    ...mapState({
      model: (state) => state.houseInfo.houPortInfo.find((v) => v.portType === PORT_CODE_AJK),
      resblockName: (state) => state.houseInfo.houDelVO.resblockName,
      houDelVO: (state) => state.houseInfo.houDelVO,
      houDelId: (state) => state.houseInfo.houDelVO.id,
    }),

    // 户室号匹配文案
    hshTips() {
      if (!this.portVO.portResblockName) return '(未匹配)';
      if (this.hushihaoFilledPrue) return '(已匹配)';
      return `(未匹配 - ${this.portVO.huShiHao ? '请输入户室号' : '请选择户室号'})`;
    },

    // 纯 户室号有没有填
    hushihaoFilledPrue() {
      let info = this.portVO;
      if (!info.portResblockName) return false;
      if (!info.hallRoomNumber || info.hallRoomNumber.length == 0) {
        return false;
      }
      const protFilledList = hallRoomNumber.map((v) => v.key).filter((key) => this.isValidValue(info[key]));
      let r = protFilledList.length >= info.hallRoomNumber.length;
      return r;
    },

    selectDisabled() {
      return (key) => {
        if (this.portVO.hallRoomNumber.length == 0) {
          return true;
        }
        if (!this.portVO.portResblockName) return true;

        let hasBuild = this.portVO.hallRoomNumber.find((v) => v.key == 'portBuild');
        let hasUnit = this.portVO.hallRoomNumber.find((v) => v.key == 'portUnit');

        if (key == 'portUnit') {
          if (hasBuild && !this.portVO.portBuild) return true;
          return false;
        }
        if (key == 'portDoorNum') {
          if (hasBuild && !this.portVO.portBuild) return true;
          if (hasUnit && !this.portVO.portUnit) return true;
          return false;
        }
      };
    },
  },

  beforeDestroy() {
    if (this.handleTimer) {
      clearTimeout(this.handleTimer);
      this.handleTimer = null;
    }
  },

  methods: {
    renderPort(data) {
      Object.assign(this.portVO, data);

      // 可推不一定填写完整了(此处跟老逻辑不同)
      // this.portVO.hallRoomNumber = hallRoomNumber.filter((v) => !!data[v.key]);

      // 已匹配过小区
      if (data.portResblockName) {
        this.getHshColumn('portVO', data);
      }
    },

    setTimer(fn) {
      if (this.tryTimes >= this.totalTimes) {
        this.tryTimes = 0;
        return false;
      }
      this.tryTimes = this.tryTimes + 1;
      if (this.handleTimer) {
        clearTimeout(this.handleTimer);
        this.handleTimer = null;
      }
      this.handleTimer = setTimeout(fn, this.intervalTime);
      return true;
    },

    handleFocusHsh(way, key, kw = '') {
      const m = this[way];
      if (m.huShiHao) return;

      m.singleLoading = true;
      m.buildUnitDoorOptions = [];
      const ct = () => {
        // 需要尝试重新请求
        m.singleLoading = false;
      };

      const cb = (content) => {
        this.tryTimes = 0;
        m.singleLoading = false;

        if (content.length) {
          m.buildUnitDoorOptions = content;
        }
      };

      if (key == 'portBuild') {
        matchingBuild({
          delId: this.houDelId,
          portResblockId: m.portResblockId,
          portType: m.portType,
          type: 0,
          platformResblockId: m.platformResblockId,
          kw,
        })
          .then(cb)
          .catch(ct);
      } else if (key == 'portUnit') {
        matchingUnit({
          delId: this.houDelId,
          portResblockId: m.portResblockId,
          portType: m.portType,
          portBuildId: m.portBuildId,
          platformResblockId: m.platformResblockId,
          platformBuildId: m.platformBuildId,
          kw,
        })
          .then(cb)
          .catch(ct);
      } else if (key == 'portDoorNum') {
        matchinDoorNum({
          delId: this.houDelId,
          portResblockId: m.portResblockId,
          portBuildId: m.portBuildId,
          portUnitId: m.portUnitId,
          portType: m.portType,
          platformResblockId: m.platformResblockId,
          platformBuildId: m.platformBuildId,
          platformUnitId: m.platformUnitId,
          kw,
        })
          .then(cb)
          .catch(ct);
      }
    },

    handleChangeHsh(way, id) {
      const m = this[way];
      let key = '';
      let item = m.buildUnitDoorOptions.find((v) => {
        if (v.platformBuildId == id) {
          key = 'platformBuildId';
          return true;
        } else if (v.platformUnitId == id) {
          key = 'platformUnitId';
          return true;
        } else if (v.platformDoorNumId == id) {
          key = 'platformDoorNumId';
          return true;
        }
      });

      if (key == 'platformBuildId') {
        m.portUnit = '';
        m.portUnitId = '';
        m.platformUnitId = '';
        m.portDoorNum = '';
        m.portDoorNumId = '';
        m.platformDoorNumId = '';
      } else if (key == 'platformUnitId') {
        m.portDoorNum = '';
        m.portDoorNumId = '';
        m.platformDoorNumId = '';
      }

      Object.assign(m, item);
      const arr = ['portBuild', 'portUnit', 'portDoorNum'].filter((v) => !!this.portVO[v]);
      if (arr.length >= this.portVO.hallRoomNumber.length) {
        this.verifyBuildSize();
      }
    },

    verifyBuildSize() {
      this.portVO.isMatchingBuild = true;

      matchingBuild({
        delId: this.houDelId,
        portResblockId: this.portVO.portResblockId,
        portType: this.portVO.portType,
        type: 1,
        platformResblockId: this.portVO.platformResblockId,
        portDoorNumId: this.portVO.portDoorNumId,
        platformDoorNumId: this.portVO.platformDoorNumId,
      })
        .then((content) => {
          this.portVO.isMatchingBuild = false;

          let obj = JSON.parse(content);
          if (obj.attr && obj.attr.mianJi && obj.attr.mianJi.value) {
            let buildSize = obj.attr.mianJi.value;
            // this.$message.info('当前已帮您匹配到该房源的面积，此时面积不可修改');
            this.myBuildSize = buildSize;
            this.portVO.buildSizeLocked = true;
          } else {
            this.portVO.buildSizeLocked = false;
          }
        })
        .catch(() => {
          this.portVO.buildSizeLocked = false;
        });
    },

    // 获取某小区的户室号栏目数
    getHshColumn(way, info) {
      const m = this[way];
      m.huShiHao = false;
      m.buildUnitDoorOptions = [];

      m.hallRoomLoading = true;
      this.resetHuShiHao(way);

      if (m.hallRoomNumber.length) {
        m.hallRoomNumber = [];
      }

      return matchingBuild({
        delId: this.houDelId,
        portResblockId: info.portResblockId,
        portType: m.portType,
        type: 1,
        platformResblockId: info.platformResblockId,
      })
        .then((content) => {
          // 成功查询到
          this.tryTimes = 0;

          m.hallRoomLoading = false;
          if (content == '{}') {
            return;
          }
          let data = JSON.parse(content);

          const keys = ['isShowBuilding', 'isShowUnit', 'isShowHouse'];
          const arr = hallRoomNumber.filter((item, i) => data[keys[i]] == 1);
          m.hallRoomNumber = arr;

          m.huShiHao = data.huShiHao;
          // console.log("是否支持手动", data.huShiHao);

          // 手动输入则可以开始校验价格了
          if (data.huShiHao) {
            this.portVO.buildSizeLocked = false;
          }
        })
        .catch(() => {
          let setSuccess = this.setTimer(() => {
            this.getHshColumn(way, info);
            // console.log("重新匹配几栏。。。");
          });
          if (!setSuccess) {
            m.hallRoomLoading = false;
          }
        });
    },

    // 重试户室号栏目
    handleRetryColumn() {
      this.getHshColumn('portVO', this.portVO);
    },

    resetHuShiHao(way) {
      const m = this[way];
      m.portBuild = '';
      m.portBuildId = '';
      m.portUnit = '';
      m.portUnitId = '';
      m.portDoorNum = '';
      m.portDoorNumId = '';

      m.platformBuildId = '';
      m.platformUnitId = '';
      m.platformDoorNumId = '';

      m.huShiHao = false;
    },

    remoteMethod(key) {
      return (query) => {
        if (!query) return;
        this.handleFocusHsh('portVO', key, query);
      };
    },

    // 保存端口匹配信息
    save() {
      if (this.modifiedCount > 0) return Promise.resolve();

      const { portVO: item } = this;
      const result = [
        {
          delId: this.houDelId,
          portResblockName: item.portResblockName,
          portBuild: item.portBuild,
          portUnit: item.portUnit,
          portDoorNum: item.portDoorNum,

          platformResblockId: item.platformResblockId,
          platformBuildId: item.platformBuildId,
          platformUnitId: item.platformUnitId,
          platformDoorNumId: item.platformDoorNumId,

          huShiHao: item.huShiHao,
          buildSizeLocked: item.buildSizeLocked,
          totalPricesPassed: item.totalPricesPassed,
          totalPricesIgnore: item.totalPricesIgnore,

          totalPrice: this.setTotalPrices(this.houDelVO, item.totalPrice),
          buildingSize: item.buildingSize,
          publishSize: item.publishSize,

          portTags: item.portTags,
          portType: item.portType,
          onePushFlag: '0',
          delPercentage: '1',
          delegationType: 'SALES',
        },
      ];

      return saveHouPortInfo(result).then(({ isSuccess, errorMessage }) => {
        if (!isSuccess) {
          return Promise.reject({ errorMessage: errorMessage || '户室号保存失败！' });
        }
      });
    },
  },
};
</script>

<style scoped>
.reject-input >>> .el-input__inner {
  border-color: red;
}
.tips1 {
  line-height: 2;
}
.tips2 {
  font-size: 12px;
  font-weight: 500;
  color: #ef4d4d;
  line-height: 3;
  text-indent: 110px;
}
</style>
